package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-19
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto loginDto) {
//        先判断参数是否为空
        if(loginDto==null|| StringUtils.isEmpty(loginDto.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        根据姓名查询信息


        LambdaQueryWrapper<AdUser> query=new LambdaQueryWrapper<>();
        query.eq(AdUser::getName,loginDto.getName());
        AdUser one = this.getOne(query);
//        将查询到的盐和前端传过来的密码加密对比数据库的密码
        String password=loginDto.getPassword()+one.getSalt();
        String md5 = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!md5.equals(one.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        生成token
        Map<String,Object> map=new HashMap<>();
        map.put("userId",one.getId());
        String token = AppJwtUtil.getToken(map);
//        记得给前端=一个正确的相应格式
        AdUser user=new AdUser();
        user.setName(one.getName());
        Map<String,Object> objectMap=new HashMap<>();
        objectMap.put("token",token);
        objectMap.put("user",user);



        return ResponseResult.okResult(objectMap);
    }
}
